#!/usr/bin/perl -w
#
#

use strict;
use warnings;
use utf8;

use FindBin;
use lib "$FindBin::Bin/../../lib";

use File::Spec::Functions;

my $base = catdir( $FindBin::Bin, '../..' );

use Config::General;
use DBI;
use Log::Log4perl;

use MTT::Schema;
use MTT::Libs::Masks;
use MTT::Libs::AlarmRun;

Log::Log4perl->init( catfile($base, 'logger.conf') );
my $log = Log::Log4perl->get_logger();

eval {
	my $alarm_log = Log::Log4perl->get_logger('alarms');

	my $mtt_conf = catfile($base, 'mtt.conf');
	my %cfg = Config::General->new( catfile($base, 'mtt.conf') )->getall();

	my $schema_mtt = MTT::Schema->connect( $cfg{'Model::DBIC'}->{connect_info} );

	my $ci = $cfg{CallDB}->{connect_info};
	my $dbh_call = DBI->connect(
		$ci->{dsn},
		$ci->{user},
		$ci->{password}
	) || die DBI->errstr;
	$dbh_call->do( $ci->{on_connect_do} );

	$ci = $cfg{StatDB}->{connect_info};
	my $dbh_stat = DBI->connect(
		$ci->{dsn},
		$ci->{user},
		$ci->{password}
	) || die DBI->errstr;
	$dbh_stat->do( $ci->{on_connect_do} );
		
	my $masks = MTT::Libs::Masks->new(dbh => $schema_mtt->storage->dbh);

	my $alarms = MTT::Libs::AlarmRun->new({
			log => $log,
			alarm_log  => $alarm_log,
			alarm_script => $cfg{alarm_script},
			schema_mtt => $schema_mtt,
			schema_stat => $dbh_stat,
			schema_call => $dbh_call,
			masks => $masks,
			host  => $cfg{Mailer}->{host},
		});

	$alarms->run();
};

if ($@) {
	if($log) {
		$log->fatal($@);
	}
	die $@;
}

